#!/bin/bash
#2020年7月6日22:21:18
#auto backup mysql database
#by author www.jfedu.net
########################
SQL_DB="$*"
SQL_USR="backup"
SQL_PWD="bak123456"
SQL_CMD="/usr/bin/mysqldump"
BAK_DIR="/data/backup/`date +%F`"
if [ $# -eq 0 ];then
	echo -e "\033[32m----------------\033[0m"
	echo -e "\033[32mUsage:{/bin/bash $0 jfedu001|jfedu002|all|help}\033[0m"
	exit
fi

if [ $UID -ne 0 ];then
	echo "Exec backup scripts,must to be use root."
	exit
fi
if [ ! -d $BAK_DIR ];then
	mkdir -p $BAK_DIR
fi

if [ $SQL_DB == "all" ];then
	for SQL_DB in $(/usr/bin/mysql -u$SQL_USR -p$SQL_PWD -e "show databases;")
	do
		$SQL_CMD -u$SQL_USR -p$SQL_PWD $SQL_DB >$BAK_DIR/${SQL_DB}.sql		
		if [ $? -eq 0 ];then
			echo -e "\033[32m----------------\033[0m"
			echo -e "\033[32mThe mysql database $SQL_DB backup successfully.\033[0m"
			echo
			echo "ls -l $BAK_DIR/"
			ls -l $BAK_DIR/
		else
			echo "The mysql database $SQL_DB backup falied."
			rm -rf $BAK_DIR/${SQL_DB}.sql
		
		fi		
	done
	exit
fi

for SQL_DB in $SQL_DB
do
	$SQL_CMD -u$SQL_USR -p$SQL_PWD $SQL_DB >$BAK_DIR/$SQL_DB.sql
	if [ $? -eq 0 ];then
		echo -e "\033[32m----------------\033[0m"
		echo -e "\033[32mThe mysql database $SQL_DB backup successfully.\033[0m"
		echo
		echo "ls -l $BAK_DIR/"
		ls -l $BAK_DIR/
	else
		echo "The mysql database $SQL_DB backup falied."
		rm -rf $BAK_DIR/${SQL_DB}.sql
		while true
		do
			echo
			read -p "Please retry enter database name: " INPUT
			/usr/bin/mysql -u$SQL_USR -p$SQL_PWD -e "show databases;"|grep -ai "$INPUT"
			if [ $? -eq 0 ];then
				break
			fi
		done
	
	fi
done
